import { Blog } from '../model/Blog.js'
import { Op } from 'sequelize';

const fn_list = async (ctx, next) => {
    const keyword = ctx.request.query.keyword;

    let where = {};
    if (keyword) {
        where = {
            [Op.or]: [
                { headline: { [Op.like]: `%${keyword}%` } },
                { digest: { [Op.like]: `%${keyword}%` } },
                { content: { [Op.like]: `%${keyword}%` } },
                { classify: { [Op.like]: `%${keyword}%` } },
                { author: { [Op.like]: `%${keyword}%` } },
                { creatTime: { [Op.like]: `%${keyword}%` } }

            ]
        }
    }
    const blogs = await Blog.findAll({ where })
    ctx.body = {
        code: 1000,
        msg: '获取博客成功！',
        data: blogs
    }
}
const fn_getById = async (ctx, next) => {
    const id = ctx.params.id
    const blog = await Blog.findByPk(id)
    ctx.body = {
        code: 1000,
        msg: '获取数据成功！',
        data: blog
    }
}
const fn_add = async (ctx, next) => {
    const blog = ctx.request.body
    await Blog.create(blog)
    ctx.body = {
        code: 1000,
        msg: '添加博客成功！',
        data: null
    }
}
const fn_update = async (ctx, next) => {
    const id = ctx.params.id
    const blog = ctx.request.body
    await Blog.update(blog, {
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 1000,
        msg: '修改博客成功！',
        data: null
    }
}
const fn_delete = async (ctx, next) => {
    const id = ctx.params.id
    await Blog.destroy({
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 1000,
        msg: '删除博客成功！',
        data: null
    }
}

export default [
    {
        method: 'get',
        url: '/blog',
        fn: fn_list
    },
    {
        method: 'get',
        url: '/blog/:id',
        fn: fn_getById
    },
    {
        method: 'post',
        url: '/blog',
        fn: fn_add
    },
    {
        method: 'put',
        url: '/blog/:id',
        fn: fn_update
    },
    {
        method: 'delete',
        url: '/blog/:id',
        fn: fn_delete
    },
]